/**
 * Copyright &copy; 2012-2016 <a href="https://github.com/thinkgem/ccjzxyxt">ccjzxyxt</a> All rights reserved.
 */
package cn.net.dckj.modules.cms.web.front;

import cn.net.dckj.common.config.Global;
import cn.net.dckj.common.persistence.JsonData;
import cn.net.dckj.common.web.BaseController;
import cn.net.dckj.modules.sys.entity.Office;
import cn.net.dckj.modules.sys.entity.Role;
import cn.net.dckj.modules.sys.entity.User;
import cn.net.dckj.modules.sys.service.SystemService;
import com.google.common.collect.Lists;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.List;

/**
 * 用户注册Controller
 */
@Controller
@RequestMapping(value = "${frontPath}")
public class FrontRegisterController extends BaseController {

    @Autowired
    private SystemService systemService;

    /**
     * 前端注册用户（保存用户信息）
     */
    @RequestMapping(value = "register", method = RequestMethod.POST)
    @ResponseBody
    public JsonData registerJson(User user, HttpServletRequest request, HttpServletResponse response, Model model) {
        JsonData jsonData = new JsonData();
        if (Global.isDemoMode()) {
            jsonData.setSuccess(false).setMessage("演示模式，不允许操作！");
            return jsonData;
        }
        // 修正引用赋值问题，不知道为何，Company和Office引用的一个实例地址，修改了一个，另外一个跟着修改。
        user.setCompany(new Office(request.getParameter("company.id")));
        User person = systemService.getUserByLoginName(user.getLoginName());
        if (person != null) {
            jsonData.setSuccess(false).setMessage("用户名已存在！");
            return jsonData;
        }
        if ("2".equals(user.getUserType()) || "3".equals(user.getUserType())) {
            user.setOffice(new Office(user.getOfficeId()));//
        } else {
            user.setOffice(new Office("200"));//校外人员
        }
        user.setPassword(systemService.entryptPassword(user.getPassword()));
        user.setCreateBy(new User("1"));
        user.setUpdateBy(new User("1"));
        // 角色数据有效性验证，过滤不在授权内的角色
        List<Role> roleList = Lists.newArrayList();
        Role role = systemService.getRole(user.getUserType());
        roleList.add(role);
        user.setRoleList(roleList);
        // 保存用户信息
        systemService.saveUser(user);
        // 清除当前用户缓存
        /*if (user.getLoginName().equals(UserUtils.getUser().getLoginName())){
            UserUtils.clearCache();
		}*/
        jsonData.setSuccess(true).setMessage("用户" + user.getLoginName() + "注册成功！");
        return jsonData;
    }
}
